﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpenseSystem.Common;
using ExpenseSystem.Common.BaseModel;
using ExpenseSystem.DataUpdater;
using ExpenseSystem.Fether;
using ExpenseSystem.Model;
using ExpenseSystem.Core.DataAddOn;
using System.Web;
namespace ExpenseSystem.Core.BaseModules
{
    public class CodeGeneratorManager
    {
        protected string tran = HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString();

        public CodeGeneratorManager() { }
        public string GetSeqWithUpdate(long site,string code,out string message)
        {
            NormalDataUpdater<CodeGeneratorModel> updater = new NormalDataUpdater<CodeGeneratorModel>();
            CodeGeneratorFetcher fetcher = new CodeGeneratorFetcher();
            CodeGeneratorModel codeGeneratorModel = fetcher.GetByCode(site,code,out message);
            if (codeGeneratorModel == null)
            {
                message = String.Format("CodeGenerator not support the code {0}", code);
                LogHelper.Info(this.GetType().Name, message);
                return "";
            }
            int max = (int)Math.Pow(10, codeGeneratorModel.SeqLength);
            if (codeGeneratorModel.Seq >= max)
            {
                message = String.Format("seq {0} is too big", codeGeneratorModel.Seq);
                LogHelper.Info(this.GetType().Name, message);
                return "";
            }
            string resultStr = String.Format("{0}{1}{2}{3}{4}",
                codeGeneratorModel.Var1 == null ? "" : codeGeneratorModel.Var1,
                codeGeneratorModel.Var2 == null ? "" : codeGeneratorModel.Var2,
                codeGeneratorModel.Var3 == null ? "" : codeGeneratorModel.Var3,
                codeGeneratorModel.DateFormat == null ? "" : DateTime.Today.ToString(codeGeneratorModel.DateFormat),
                (Math.Pow(10, codeGeneratorModel.SeqLength) + codeGeneratorModel.Seq + 1).ToString().Substring(1, codeGeneratorModel.SeqLength));
            codeGeneratorModel.Seq += 1;
            bool b =updater.Save(codeGeneratorModel, tran, fetcher, out message);
            if (b)
                return resultStr;
            else
                return "";
        }
    }
}
